#!/usr/bin/python

#Created by turk 2017-04-05
#Jupiter Server [PYTHON]
#Version 1.0 

import os
import commands
import sys
import logging
import time
import socket
import traceback

WORKPATH='/root/nyx'
LOGPATH=WORKPATH + '/log'
LOGFILE=LOGPATH + '/' +  str(int(time.time())) + '.nyx.log'
DESTPATH='/home/pertest/dest'
SERVERIP='192.168.5.28'
#Logger
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',  
                    datefmt='%Y-%m-%d %H:%M:%S',  
                    filename=LOGFILE,  
                    filemode='w')  
console = logging.StreamHandler()  
console.setLevel(logging.INFO)  
# set print format
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')  
console.setFormatter(formatter)  
#
logging.getLogger('').addHandler(console)  
logger = logging.getLogger('jupiter')                     
                    

#sort
def compare(x, y):
    stat_x = os.stat(DATAPATH + "/" + x)
    stat_y = os.stat(DATAPATH + "/" + y)
    if stat_x.st_ctime < stat_y.st_ctime:
        return -1
    elif stat_x.st_ctime > stat_y.st_ctime:
        return 1
    else:
        return 0

def StartServer(PORT,DATAPATH):
    
    ip_port = (SERVERIP,int(PORT))
    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sk.bind(ip_port)
    #max connect number
    sk.listen(5)
    #Loop
    while True:
        print ('server waiting...')
        logger.info('server waiting... ') 
        #
        conn,addr = sk.accept()
        
        logger.info('client accept.') 
        #
        #client_data = conn.recv(1024)
        #
        #print (str(client_data,'utf8'))
        #
        
        Loop = True
        try:
            while Loop:
                #loop dir
                files = os.listdir(DATAPATH)  
                files.sort(compare)
                
                for f in files:
                    if(os.path.isdir(DATAPATH + '/' + f)):
                        if(f[0] == '.'):  
                            pass  
                        else:
                            dirList.append(f)  
                        
                    #if(os.path.isfile(DATAPATH + '/' + f) and f.endswith(".COMPLETED")):  
                    if(os.path.isfile(DATAPATH + '/' + f)):  
                        logger.info('start read file and transmission data [%s]' %(f)) 
                        file_object = open(DATAPATH + '/' + f)
                        try:
                            for line in file_object:
                                conn.sendall(bytes(line))
                        except Exception:
                            logger.exception('Send Data Exception')
                            #logger.error(traceback.print_exc())
                            time.sleep(2)
                            Loop = False
                            break
                        finally:
                            file_object.close()
                            os.remove(DATAPATH + '/' + f)
                            logger.info('transmission data OK and delete file [%s]' %(f))
                        
                time.sleep(2)   
            
            
        except Exception:
            logger.exception('Read File Exception')
            #logger.error(traceback.print_exc())
            time.sleep(2)
        finally:
            conn.close()
            
if __name__ == '__main__':
    print sys.argv  
    if len(sys.argv) < 3:
        print "Usage:<PORT> <DOCNAME>"
        sys.exit()
    
    PORT=sys.argv[1]
    DOCNAME=sys.argv[2]
    DATAPATH = DESTPATH + '/' + DOCNAME
    
    StartServer(PORT,DATAPATH)
     
    print 'COMPLATE'
